import React, { useEffect, useState, useRef, Children, cloneElement } from 'react';
import Input from '../Input';
import Position from './Position';
import PropTypes from 'prop-types';

import IMG1 from '../Input/bz.png';
import IMG2 from '../Input/bql.png';

import './Select.css';

function Select(props) {
  const { children, style, defaultValue, getPopupContainer } = props;
  // 是否显示下拉框
  const [visible, setVisible] = useState(false);
  // 当前选中的值
  const [data, setData] = useState({ value: defaultValue, label: '' });
  const inputRef = useRef();
  const selectRef = useRef();

  const bindBodyClick = (e) => {
    if (e.target === inputRef.current) return;
    setVisible(false);
  };
  //   子元素发生点击
  const handleClick = (data) => {
    console.log('data ===> ', data);
    setData(data);
  };

  useEffect(() => {
    document.addEventListener('click', bindBodyClick, false);
  }, [visible]);

  // 初始化完成时监听 (超出可视区域消失)
  useEffect(() => {
    const container = getPopupContainer && getPopupContainer();
    const observerRefValue = selectRef.current; // <-- save ref value 防止影响清理
    var observer = null;
    if (container) {
      observer = new IntersectionObserver(
        (entries) => {
          // console.log('entries ===> ', entries);
          // 元素消失在可视区域
          if (!entries[0].isIntersecting) {
            setVisible(false);
          }
        },
        { root: container }
      );
      observer.observe(observerRefValue);
    }

    return () => {
      observer && observer.unobserve(observerRefValue);
    };
  }, []);

  // 查找defalut对应的value 默认值
  useEffect(() => {
    if (!defaultValue) return;
    const i = children.findIndex((n) => n.props.value === defaultValue);
    if (i > -1) {
      setData(children[i].props);
    }
  }, [defaultValue, children]);

  return (
    <div style={style} ref={selectRef}>
      <Input
        onClick={() => {
          setVisible(true);
        }}
        value={data.label}
        ref={inputRef}
        style={{ width: '100%', marginTop: '30px' }}
        placeholder="请输入"
        suffix={<img src={IMG2} alt="" />}
        prefix={<img src={IMG1} alt="" />}
      />
      {visible && (
        //    className={`select_childrenBox`}
        <Position targetRef={selectRef} getPopupContainer={getPopupContainer}>
          {/* 这个api可以直接对children进行遍历,而不用关心children是否为数组,
            当children为一个数组时,遍历的每一项都是ReactNode, 
            当children本身为ReactNode时,children将被返回 */}
          {Children.map(children, (child) => {
            // 为children 添加 handleClick 事件
            return cloneElement(child, {
              handleClick,
              defaultValue: data.value,
            });
          })}
        </Position>
      )}
    </div>
  );
}

// children, style, defaultValue, getPopupContainer
Select.prototype = {
  style: PropTypes.object,
  defaultValue: PropTypes.string,
  getPopupContainer: PropTypes.func,
  children: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
};

export default Select;
